package com.example.applicationjet

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.applicationjet.lifecycle.ActivityObserver
import com.example.applicationjet.viewmodel.MyViewModel

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    lateinit var mLiveData : MutableLiveData<String>;
    lateinit var viewModel: MyViewModel;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //添加lifecycle监听
        lifecycle.addObserver(ActivityObserver())
        //
        mLiveData = MutableLiveData()
        //带声明周期的数据监测
//        mLiveData.observe(this, Observer {
//            Log.i(TAG, "observe: " + it);
//        })
        //不带声明周期的数据监测
        mLiveData.observeForever(Observer {
            Log.i(TAG, "observe: " + it);
        })
        //ViewModel
        val viewModelProvider = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory())
         viewModel = viewModelProvider.get(MyViewModel::class.java)
        viewModel.getLiveData().observe(this, Observer {
            Log.i(TAG, "viewModel observe: " + it);
        })
    }

     protected override fun onStart() {
        super.onStart();
        Log.i(TAG, "onStart: ");
        mLiveData.setValue("onStart");//活跃状态，会回调onChanged。并且value会覆盖onCreate、onStop中设置的value
    }

    protected override fun onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
        mLiveData.setValue("onResume");//活跃状态，回调onChanged
    }
    protected override fun onPause() {
        super.onPause();
        Log.i(TAG, "onPause: ");
        mLiveData.setValue("onPause");//活跃状态，回调onChanged
    }
    protected override fun onStop() {
        super.onStop();
        Log.i(TAG, "onStop: ");
        mLiveData.setValue("onStop");//非活跃状态，不会回调onChanged。后面变为活跃时，value被onStart中的value覆盖
    }
    protected override fun onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
        mLiveData.setValue("onDestroy");//非活跃状态，且此时Observer已被移除，不会回调onChanged
    }

    fun clickAdd(view: View) {
        viewModel.set(System.currentTimeMillis().toString())
    }
    fun clickSub(view: View) {

    }
}

